//
//  RecFirstViewController.m
//  A段项目
//
//  Created by dlios on 15/7/10.
//  Copyright (c) 2015年 dlios. All rights reserved.
//

#import "RecFirstViewController.h"
#import "SANetWorkingTask.h"
#import "MyScrollView.h"
#import "RecFirModel.h"
#import "RecSecViewController.h"
#import "TouchImage.h"
#import "RecFirTableViewCell.h"
#import "RecSecTableViewCell.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "RecThiViewController.h"
#import "RecForViewController.h"
#import "MJRefresh.h"
#import "BaseHeader.h"
#import "SearchViewController.h"
#import "DownView.h"


#define heigh self.view.frame.size.height

@interface RecFirstViewController ()<MyScrollViewDelegate, UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain) NSMutableArray *scrollArray;
@property (nonatomic, retain) UITableView *table;
@property (nonatomic, retain) NSMutableArray *tableArray;
@property (nonatomic,assign) NSInteger detailsPageCount;
@property (nonatomic,retain) UIScrollView *topView;
@property (nonatomic,retain) DownView *downView;
@property (nonatomic, retain) NSMutableArray *cancelArr;
@property (nonatomic, retain) NSMutableArray *addArr;
@property (nonatomic, retain) NSMutableArray *buttonArr;
@property (nonatomic, retain) MyScrollView *scroll;


@end

@implementation RecFirstViewController

- (void)dealloc
{
    [_scroll release];
    [_scrollArray release];
    [_table release];
    [_tableArray release];
    [_topView release];
    [_downView release];
    [_cancelArr release];
    [_addArr release];
     [_buttonArr release];
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        self.scrollArray = [NSMutableArray array];
        self.tableArray = [NSMutableArray array];
        self.cancelArr = [NSMutableArray array];
        self.addArr = [NSMutableArray array];
         self.buttonArr = [NSMutableArray array];
        self.detailsPageCount = 2;
        [self getUrl];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
     self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.title = @"推荐";
     UIBarButtonItem *search = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"search.png"] style:UIBarButtonItemStyleDone target:self action:@selector(search)];
     self.navigationItem.rightBarButtonItem = search;
     [search release];
     self.view.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:0.8];

    [self createButton];
    [self createScroll];
    [self connectTable];
       // Do any additional setup after loading the view.
}



#pragma mark -
#pragma mark 所有栏目接口
- (void)getUrl
{
    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
    NSArray * arrac = [defaults objectForKey:@"cancell"];
    NSArray * arrra = [defaults objectForKey:@"add"];
    if (!arrac) {
        NSDictionary *dic1 = @{@"title": @"改装升级", @"url": @"http://mi.xcar.com.cn/interface/xcarapp/getdingyue.php?limit=10&offset=0&type=83757&ver=6.1.4", @"type": @83757};
        NSDictionary *dic2 = @{@"title": @"奇闻车事",  @"url": @"http://mi.xcar.com.cn/interface/xcarapp/getdingyue.php?limit=10&offset=0&type=1540&ver=6.1.4", @"type": @1540};
        NSDictionary *dic3 = @{@"title": @"汽车音响", @"url": @"http://mi.xcar.com.cn/interface/xcarapp/getdingyue.php?limit=10&offset=0&type=985&ver=6.1.4", @"type": @985};
        NSDictionary *dic4 = @{@"title": @"概念车",  @"url": @"http://mi.xcar.com.cn/interface/xcarapp/getdingyue.php?limit=10&offset=0&type=18534&ver=6.1.4", @"type": @18534};
     
        NSDictionary *dic7 = @{@"title": @"视频",  @"url": @"http://mi.xcar.com.cn/interface/xcarapp/getdingyue.php?limit=10&offset=0&type=144998&ver=6.1.4", @"type": @144998};
        NSDictionary *dic8 = @{@"title": @"行情",  @"url": @"http://a.xcar.com.cn/interface/6.0/getNewsList.php?cityId=64&limit=10&offset=0&type=5&ver=6.1.4", @"type": @5};
        NSDictionary *dic9 = @{@"title": @"购车技巧",  @"url": @"http://mi.xcar.com.cn/interface/xcarapp/getdingyue.php?limit=10&offset=0&type=76395&ver=6.1.4", @"type": @76395};
        NSDictionary *dic10 = @{@"title": @"评测",  @"url": @"http://a.xcar.com.cn/interface/6.0/getNewsList.php?limit=10&offset=0&type=3&ver=6.1.4", @"type": @3};
        NSDictionary *dic12 = @{@"title": @"新车上市",  @"url": @"http://mi.xcar.com.cn/interface/xcarapp/getdingyue.php?limit=10&offset=0&type=3&ver=6.1.4", @"type": @3};
   
        NSDictionary *dic14 = @{@"title": @"导购",  @"url": @"http://a.xcar.com.cn/interface/6.0/getNewsList.php?limit=10&offset=0&type=4&ver=6.1.4", @"type": @4};
        NSDictionary *dic15 = @{@"title": @"激情赛车",  @"url": @"http://mi.xcar.com.cn/interface/xcarapp/getdingyue.php?limit=10&offset=0&type=33&ver=6.1.4", @"type": @33};
        NSDictionary *dic18 = @{@"title": @"新闻",  @"url": @"http://a.xcar.com.cn/interface/6.0/getNewsList.php?limit=10&offset=0&type=2&ver=6.1.4", @"type": @2};
   
        
        NSArray *arr = @[dic1, dic2, dic4, dic7];
        self.cancelArr = [NSMutableArray arrayWithArray:arr];
        [defaults setObject:_cancelArr forKey:@"cancell"];
        
        NSArray *array = @[dic3, dic8, dic9, dic10, dic12, dic14, dic15, dic18];
        self.addArr = [NSMutableArray arrayWithArray:array];
        [_addArr addObject:dic3];
        [defaults setObject:_addArr forKey:@"add"];
        
    } else
    {
        self.cancelArr = [NSMutableArray arrayWithArray:arrac];
        self.addArr = [NSMutableArray arrayWithArray:arrra];
    }

}



#pragma mark -
#pragma mark 栏目选择
- (void)createButton
{
    self.topView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth  - 50, 50)];
     _topView.showsHorizontalScrollIndicator = NO;
    _topView.contentSize = CGSizeMake(self.cancelArr.count * 85 + 80, 0);
    [self.view addSubview:_topView];
    [_topView release];
    _topView.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:0.8];
    
    UIButton *mainBu = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
    [_topView addSubview:mainBu];
    [mainBu release];
    
    [mainBu setTitle:@"要闻" forState:UIControlStateNormal];
    [mainBu setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
     mainBu.tag = 25;
//    mainBu.titleLabel.font = [UIFont systemFontOfSize:15];
    [mainBu addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    int i = 0;
     self.buttonArr = [NSMutableArray array];
    for (NSDictionary *dic in self.cancelArr) {
         UIButton *aButton = [[UIButton alloc] initWithFrame:CGRectMake(i  * 85 + 55, 0, 80, 50)];
         [self.buttonArr addObject:aButton];
         aButton.tag = i + 1;
        [aButton setTitle:[dic objectForKey:@"title"] forState:UIControlStateNormal];
        [aButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//        aButton.titleLabel.font = [UIFont systemFontOfSize:15];
        [aButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.topView addSubview:aButton];
        [aButton release];
        i++;
        
    }

    
    UIButton *down = [[UIButton alloc] initWithFrame:CGRectMake(ScreenWidth - 50, 0, 50, 50)];
    [down setImage:[UIImage imageNamed:@"向下.png"] forState:UIControlStateNormal];
    down.tag = 1;
    [self.view addSubview:down];
    [down release];
    [down addTarget:self action:@selector(downAction:) forControlEvents:UIControlEventTouchUpInside];
    
    self.downView = [[[DownView alloc] initWithFrame:CGRectMake(0, 50, ScreenWidth, ScreenHeidth / 3 * 1.5)] autorelease];
    _downView.upArr = self.cancelArr;
    _downView.downArr = self.addArr;
    _downView.backgroundColor = [UIColor whiteColor];
        
     
}




- (void)buttonAction:(id)sender
{
    UIButton *bu = (UIButton *)sender;
     if (bu.tag == 25) {
          [bu setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
          _table.tableHeaderView = _scroll;
          
     } else
     {
          UIButton *main = (UIButton *)[_topView viewWithTag:25];
          [main setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
          _table.tableHeaderView = nil;
     }
     for (int i = 0; i < self.cancelArr.count; i++) {
          if (bu.tag == i + 1) {
               [bu setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
               
          } else {
             
               [[self.buttonArr objectAtIndex:i] setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
          }
     }
    if (bu.tag != 25) {
        NSDictionary *dic = [self.cancelArr objectAtIndex:bu.tag - 1];
        [SANetWorkingTask request:[dic objectForKey:@"url"] parmater:nil block:^(NSDictionary *result) {
            NSArray *arr = [result objectForKey:@"newsList"];
            self.tableArray = [NSMutableArray array];
            [_tableArray addObjectsFromArray:arr];
            [_table reloadData];
            
        }];
    } else
    {
        [SANetWorkingTask request:@"http://api.ycapp.yiche.com/appnews/toutiaov53/?platform=1&length=20&page=1" parmater:nil block:^(NSDictionary *result) {
            NSDictionary *bigDic = [result objectForKey:@"data"];
            NSArray *arr = [bigDic objectForKey:@"list"];
             self.tableArray = [NSMutableArray array];
            for (NSDictionary *dic in arr) {
                NSString *type = [NSString stringWithFormat:@"%@", [dic objectForKey:@"type"]];
                if ([type isEqualToString:@"1"] || [type isEqualToString:@"3"]) {
                    [_tableArray addObject:dic];
                }
            }
            
            [_table reloadData];
        }];

    }
    [self.table.header beginRefreshing];
}


- (void)downAction:(id)sender
{
      _topView.contentSize = CGSizeMake(self.cancelArr.count * 85 + 80, 0);
    UIButton *butt = (UIButton *)sender;
    if (butt.tag == 1) {
         self.view.backgroundColor = [UIColor whiteColor];
        [butt setImage:[UIImage imageNamed:@"向上.png"] forState:UIControlStateNormal];
        [self.topView setHidden:YES];
        butt.tag = 2;
        UIView *background = [[[UIView alloc] initWithFrame:CGRectMake(0, _topView.frame.size.height, ScreenWidth, ScreenHeidth)] autorelease];
        background.tag = 50;
        background.backgroundColor = [UIColor lightGrayColor];
        background.alpha = 0.7;
        [self.view addSubview:background];
        [self.view addSubview:_downView];
        
    } else
    {
         [butt setImage:[UIImage imageNamed:@"向下.png"] forState:UIControlStateNormal];
         
        NSArray *arr = self.topView.subviews;
        for (UIButton *button in arr) {
            if ([button isKindOfClass:[UIButton class]]) {
                
                [button removeFromSuperview];
            }
        }
        UIButton *mainBu = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
         mainBu.tag = 25;
        [_topView addSubview:mainBu];
        [mainBu release];
        
        [mainBu setTitle:@"要闻" forState:UIControlStateNormal];
        [mainBu setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
//        mainBu.titleLabel.font = [UIFont systemFontOfSize:15];
        [mainBu addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];

        int i = 0;
        NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
        NSArray * arrac = [defaults objectForKey:@"cancell"];
         self.buttonArr = [NSMutableArray array];
        for (NSDictionary *dic in arrac) {
            UIButton *aButton = [[UIButton alloc] initWithFrame:CGRectMake(i  * 85 + 55, 0, 80, 50)];
             [self.buttonArr addObject:aButton];
            aButton.tag = i + 1;
            [aButton setTitle:[dic objectForKey:@"title"] forState:UIControlStateNormal];
            [aButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//            aButton.titleLabel.font = [UIFont systemFontOfSize:15];
            [aButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
            [self.topView addSubview:aButton];
            [aButton release];
            i++;
            
        }
         butt.tag = 1;
         self.view.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:0.8];
         [self.topView setHidden:NO];
         UIView *back = [self.view viewWithTag:50];
         [back removeFromSuperview];
         [_downView removeFromSuperview];
        
    }
    
}




- (void)search
{
    SearchViewController *sea = [[SearchViewController alloc] init];
    [self.navigationController pushViewController:sea animated:YES];
    [sea release];
}


#pragma mark -
#pragma mark 上面的滚动图片
- (void)createScroll
{
    // 网络请求
    [SANetWorkingTask request:@"http://a.xcar.com.cn/interface/6.0/getNewsList.php?limit=10&offset=0&type=1&ver=6.1.4" parmater:nil block:^(NSDictionary *result) {
        NSDictionary *bigDic = [result objectForKey:@"focusList"];
        NSArray *array = [bigDic objectForKey:@"focusImgs"];
        
        for (NSDictionary *dic in array) {
            RecFirModel *model = [[RecFirModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [_scrollArray addObject:model];
            [model release];
        }
        
        // 创建scroll
        self.scroll = [[MyScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, heigh / 3)];
        _scroll.delegate = self;
        self.table.tableHeaderView = _scroll;
        [_scroll release];
        [_scroll setScrollViewIamage:_scrollArray];
        
    }];
    
}

- (void)imageTouch:(TouchImage *)image
{
    RecSecViewController *sec = [[RecSecViewController alloc] init];
    sec.str = image.model.newsLink;
    [self.navigationController pushViewController:sec animated:YES];
    [sec release];
}




#pragma mark -
#pragma mark tableview,网络请求
- (void)connectTable
{
    self.table = [[UITableView alloc] initWithFrame:CGRectMake(0, 50, self.view.frame.size.width, heigh - 100 ) style:UITableViewStylePlain];
    [self.view addSubview:_table];
    [_table release];
    self.table.dataSource = self;
    self.table.delegate = self;
    
    [self.table addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(loadNewData:)];
    [self.table addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(loadMoreDate)];
    self.table.footer.automaticallyRefresh = NO;
    
    [_table registerClass:[RecFirTableViewCell class] forCellReuseIdentifier:@"a"];
    [_table registerClass:[RecSecTableViewCell class] forCellReuseIdentifier:@"b"];
    
    
    [SANetWorkingTask request:@"http://api.ycapp.yiche.com/appnews/toutiaov53/?platform=1&length=20&page=1" parmater:nil block:^(NSDictionary *result) {
        NSDictionary *bigDic = [result objectForKey:@"data"];
        NSArray *arr = [bigDic objectForKey:@"list"];
        for (NSDictionary *dic in arr) {
            NSString *type = [NSString stringWithFormat:@"%@", [dic objectForKey:@"type"]];
            if ([type isEqualToString:@"1"] || [type isEqualToString:@"3"]) {
                [_tableArray addObject:dic];
            }
        }
        
        [_table reloadData];
    }];
}

#pragma mark -
#pragma mark 上拉加载,下拉刷新
- (void)loadMoreDate
{
     int i = 0;
     
     for (UIButton *bu in self.buttonArr) {
          if (bu.titleLabel.textColor == [UIColor blueColor]) {
               break;
          }
          i++;
     }
     if (i == self.buttonArr.count) {
        NSString *str = [NSMutableString stringWithFormat:@"http://api.ycapp.yiche.com/appnews/toutiaov53/?platform=1&length=20&page=%ld", self.detailsPageCount];
          [SANetWorkingTask request:str parmater:nil block:^(NSDictionary *result) {
          NSDictionary *bigDic = [result objectForKey:@"data"];
          NSArray *arr = [bigDic objectForKey:@"list"];
          [_tableArray addObjectsFromArray:arr];
          [_table reloadData];
          }];
     } else
     {
          NSDictionary *dic = [self.cancelArr objectAtIndex:i];
         NSString *str = [NSMutableString stringWithFormat:@"http://mi.xcar.com.cn/interface/xcarapp/getdingyue.php?limit=10&offset=%ld&type=%@&ver=6.1.4", self.detailsPageCount - 1, [dic objectForKey:@"type"]];
          // 网络请求
          [SANetWorkingTask request:str parmater:nil block:^(NSDictionary *result) {
               NSArray *arr = [result objectForKey:@"newsList"];
               [_tableArray addObjectsFromArray:arr];
               [_table reloadData];
               
          }];
          
     }
         self.detailsPageCount += 1;
        [self.table.footer endRefreshing];
    
}

// 下拉刷新
- (void)loadNewData:(id)sender
{
        [self.table reloadData];
        [self.table.header endRefreshing];
}



#pragma mark -
#pragma mark tableview的协议
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _tableArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = [_tableArray objectAtIndex:indexPath.row];
    NSString *type = [NSString stringWithFormat:@"%@", [dic objectForKey:@"type"]];
    if ([type isEqualToString:@"3"]) {
        RecSecTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"b"];
        cell.title.text = [dic objectForKey:@"title"];
        NSArray *array = [[dic objectForKey:@"picCover"] componentsSeparatedByString:@";"];
        [cell.firShow sd_setImageWithURL:[array objectAtIndex:0]  placeholderImage:[UIImage imageNamed:@"1.jpg"]];
        [cell.secShow sd_setImageWithURL:[array objectAtIndex:1] placeholderImage:[UIImage imageNamed:@"1.jpg"]];
        [cell.thiShow sd_setImageWithURL:[array objectAtIndex:2] placeholderImage:[UIImage imageNamed:@"1.jpg"]];
        cell.sec.text = [dic objectForKey:@"src"];
         cell.commentcount.text = [NSString stringWithFormat:@"%@", [dic objectForKey:@"commentCount"]];
        return cell;

        
    } else {
        RecFirTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"a"];
        if ([dic objectForKey:@"picCover"]) {
             [cell.show sd_setImageWithURL:[dic objectForKey:@"picCover"] placeholderImage:[UIImage imageNamed:@"1.jpg"]];
             cell.title.text = [dic objectForKey:@"title"];
             cell.date.text = [dic objectForKey:@"publishTime"];
             cell.content.text = [NSString stringWithFormat:@"%@", [dic objectForKey:@"commentCount"]];
             cell.sec.text = [dic objectForKey:@"src"];
             
        } else {
             [cell.show sd_setImageWithURL:[dic objectForKey:@"newsImage"] placeholderImage:[UIImage imageNamed:@"1.jpg"]];
             cell.title.text = [dic objectForKey:@"newsTitle"];
             cell.sec.text = [dic objectForKey:@"newsCategory"];
             cell.content.text = [NSString stringWithFormat:@"%@", [dic objectForKey:@"commentCount"]];
             
        }
         return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = [_tableArray objectAtIndex:indexPath.row];
    NSString *type = [NSString stringWithFormat:@"%@", [dic objectForKey:@"type"]];
    if ([type isEqualToString:@"1"] || type.length == 6) {
        return 100;
    } else
    {
        return 130;

    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
     NSDictionary *dic = [_tableArray objectAtIndex:indexPath.row];
    NSString *type = [NSString stringWithFormat:@"%@", [dic objectForKey:@"type"]];
    if (type.length == !0) {
        if ([type isEqualToString:@"1"]) {
            RecThiViewController *detail = [[RecThiViewController alloc] init];
            detail.newsId = [dic objectForKey:@"newsId"];
            [self.navigationController pushViewController:detail animated:YES];
//             [self presentViewController:detail animated:YES completion:nil];
            [detail release];
        } else
        {
            NSString *url = [NSString stringWithFormat:@"http://api.ycapp.yiche.com/appnews/GetNewsAlbum?newsid=%@", [dic objectForKey:@"newsId"]];
            [SANetWorkingTask request:url parmater:nil block:^(NSDictionary *result) {
                NSDictionary *bigDic = [result objectForKey:@"data"];
                RecForViewController *bigPic = [[RecForViewController alloc] init];
                bigPic.array = [bigDic objectForKey:@"albums"];
                NSDictionary *dic = [_tableArray objectAtIndex:indexPath.row];
                bigPic.titleName = [dic objectForKey:@"title"];
                 UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:bigPic];
                [self presentViewController:nav animated:YES completion:nil];
                [bigPic release];
            }];
            
            
        }
    } else
    {
        RecSecViewController *webview = [[RecSecViewController alloc] init];
        webview.str = [dic objectForKey:@"newsLink"];
        [self.navigationController pushViewController:webview animated:YES];
//         [self presentViewController:webview animated:YES completion:nil];
        [webview release];
    }
   
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
